const Core = require("../../utils/core.js");
const ProjectConfig = require("../../project/project_config.js");
const Storage = require("../../utils/local_storage.js");
const Tool = require("../../utils/tool.js");

/**
 * 购物车
 */
Component({
  /**
   * 属性
   */
  properties: {
    // 购物车名称，相同名称代表相同的购物车
    name: {
      type: String,
      value: 'default'
    },
    //
    showed: {
      type: Boolean,  // 使用方式1：{{true}}
      value: true,
      optionalTypes: [String] // 使用方式2：'true'
    },
    triggerSubmit: { type: Boolean, value: false },
    /**
     * 数据格式 { id: 1, name: 'a', value: 100, amount: 1, imgUrl: 'xxx.jpg', selected: true }
     */
    triggerAdd: { type: Object, value: null },
    /**
     * 数据格式 { id: 1 }
     */
    triggerRemove: { type: Object, value: null },
    /**
     * 重新检索(获取)数据
     */
    triggerRetrieve: { type: Boolean, value: false },
    /**
     * 数据格式：
      [
        { id: 1, name: 'a', value: 100, amount: 1, imgUrl: 'xxx.jpg', describe:'每件产品5元', selected: true },
        { id: 2, name: 'b', value: 101, amount: 2, imgUrl: 'xxx.jpg', describe:'每件产品10元', selected: false },
        { id: 3, name: 'c', value: 102, amount: 3, imgUrl: 'xxx.jpg', describe:'每件产品8元', selected: true }
      ]
    */
    goods: {
      type: Array,
      value: null
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    showFlag: true, // 参见 showed
    service: ProjectConfig.Service,
    goodsInitChangeFlag: false,  // goods 改变标识，在监听 goods 中设置, 用于处理在首次监听到 properties 的变化时执行 triggerEvent 无效的问题
    goodsData: {} // 参见：goods
  },
  /**
   * 监听属性
   */
  observers: {
    'showed': function (v) {
      const _this = this;
      // showed
      if (Core.Type.IsString(v)) {
        _this.setData({ showFlag: v.toBool() })
      } else {
        _this.setData({ showFlag: v })
      }
    },
    'triggerSubmit': function (v) {
      const _this = this;
      v && _this._submit();
    },
    'triggerRetrieve': function(v){
      const _this = this;
      // 处理数据
      const goods = Storage.getStorageData('shoppingCar_' + _this.properties.name);
      _this._gain(goods, 'retrieve');
    },
    'triggerAdd': function (v) {
      if(v && v.id !== null && v.id !== undefined){
        this._add(v);
      }
    },
    'triggerRemove': function(v){
      if (v && v.id !== null && v.id !== undefined) {
        this._remove(v.id);
      }
    },
    "goods": function (goods){
      const _this = this;
      // 设置 goods 改变标识
      _this.setData({ goodsInitChangeFlag: true});
      // 处理数据
      const data = [];
      for (var item of goods) {
        data.push(item);
      }
      Storage.setStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, data);
      _this._gain(data, 'change');
    },
    'goodsData': function(v){
      const _this = this;
      // 处理数据
      const goods = Storage.getStorageData('shoppingCar_' + _this.properties.name);
      _this._gain(goods, 'change');
    }
  },
  /**
   * 生命周期
   */
  lifetimes: {
    created: function(){
      const _this = this;
    },
    attached: function () {
      const _this = this;
      // 初始化数据
      let goods = Storage.getStorageData('shoppingCar_' + _this.properties.name);
      goods = !goods ? [] : goods;
      Storage.setStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, goods);
      // 处理goods初始赋值改变
      if (_this.data.goodsInitChangeFlag) {
        _this._gain(goods, 'change');
      }
    }
  },
  /**
   * 方法
   */
  methods: {
    /**
     * 获取数据，当数据发生变化时调用
     * @eventName (retrieve/change)
     */
    _gain: function (goods, eventName) {
      const _this = this;
      // 处理数据
      let total = 0;
      let amount = 0;
      const selectedData = [];
      const allDataMap = {};
      for (var item of goods) {
        allDataMap[item.id] = item;
        if (item.selected) {
          selectedData.push(item);
          total += item.value * item.amount;
          amount++;
        }
      }
      // 激活事件
      _this.triggerEvent(
        eventName,
        {
          allData: goods,
          selectedData,
          allDataMap,
          total,  // 全部 item.value * item.amount 相加
          amount  // 全部 goods 种类数量
        }
      );
    },
    /**
     * 加入购物车
     */
    _add: function (dataItem) {
      const _this = this;
      //
      Storage.modifyStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, function (data) {
        for(let item of data){
          if (item.id === dataItem.id){
            return data;
          }
        }
        data.push(dataItem);
        return data;
      });
    },
    /**
     * 从购物车移除
     */
    _remove: function (id) {
      const _this = this;
      //
      Storage.modifyStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, function (data) {
        for (let i in data){
          const item = data[i];
          if (item.id === id){
            data.splice(i, 1);
            break;
          }
        }
        return data;
      });
    },
    /**
     * 从购物车移除
     */
    remove: function (e) {
      const _this = this;
      _this._remove(e.currentTarget.dataset.id);
    },
    /**
     * 提交(通过监听 triggerSubmit:Boolean 方式激活)
     */
    _submit: function () {
      const _this = this;
      const goods = Storage.getStorageData('shoppingCar_' + _this.properties.name);
      // 收集选择的数据
      const selectedData = [];
      for (let i in goods){
        const item = goods[i];
        if (item.selected){
          selectedData.push(item);
        }
      }
      if (selectedData.length<=0){
        Tool.showInfo('没有可提交的内容');
        return;
      }
      // 激活事件
      _this.triggerEvent(
        'submit',
        {
          allData: goods,
          selectedData,
          callback: function () {
            Storage.modifyStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, function (data) {
              return data.filter(function (item) {
                return !item.selected;
              });
            });
          }
        }
      );
    },
    /**
     * 选中与取消切换
     */
    toggle: function (e) {
      const _this = this;
      const id = e.currentTarget.dataset.id;
      //
      Storage.modifyStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, function (data) {
        for (let item of data) {
          if (item.id !== id) { continue; }
          // 选中切换
          item.selected ? item.selected = false : item.selected = true;
          break;
        }
        return data;
      });
    },
    /**
     * 放大显示图片
     */
    showImg: function (event) {
      const src = event.currentTarget.dataset.src;
      wx.previewImage({
        current: src, // 当前显示图片的http链接
        urls: [src] // 需要预览的图片http链接列表
      })
    },
    /**
     * 点击减
     */
    onSubAmount: function (e) {
      const _this = this;
      const id = e.currentTarget.dataset.id;
      //
      Storage.modifyStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, function(data){
        for (let item of data) {
          if (item.id !== id) { continue; }
          //
          if (item.amount > 1) {
            item.amount--;
          }
          break;
        }
        return data;
      });
    },
    /**
     * 点击加
     */
    onAddAmount: function (e) {
      const _this = this;
      const id = e.currentTarget.dataset.id;
      //
      Storage.modifyStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, function (data) {
        for (let item of data) {
          if (item.id !== id) { continue; }
          //
          item.amount++;
          break;
        }
        return data;
      });
    },
    /**
     * 输入
     */
    onInputAmount: function (e) {
      const _this = this;
      const id = e.currentTarget.dataset.id;
      let value = e.detail.value;
      value = '' === value ? 0 : Number(value);
      //
      Storage.modifyStorageData('shoppingCar_' + _this.properties.name, 'goodsData', _this, function (data) {
        for (let item of data) {
          if (item.id !== id) { continue; }
          //
          item.amount = value;
          break;
        }
        return data;
      });
    }
  }

})